import request from "@/untils/request";
import { defineStore } from 'pinia';
import { ElMessage } from "element-plus";

const infoCollectStore = defineStore('infoCollect', {
	state() {
		type level = '0' | '1' | '2' | '3' | '4' | '5';
		return {
			form: {
				infoId: -1 as number,
				infoType: 'other' as 'file' | 'other',
				infoClass: '0' as level,
				infoContent: '' as string,
				infoDeadline: '' as string,
				infoFormat: '' as string,
				infoSource: '外部' as '内部' | '外部',
				infoProvider: '' as string,
				infoProvideTime: '' as string,
				infoCollector: '' as string,
				infoCollectTime: '' as string,
			},
		}
	},
	actions: {
		async submitCollection() {
			const regDate = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/;
			if (regDate.test(this.form.infoCollectTime) === false || regDate.test(this.form.infoProvideTime) === false || regDate.test(this.form.infoDeadline) === false) {
				ElMessage.error('日期格式不正确');
				return;
			}
			request.post('infoCollection/save', this.form).then((res: any) => {
				if (res.data.code === 0) {
					ElMessage.success('上传成功');
					Object.keys(this.form).forEach(key => {
						this.initForm();
					});
				} else ElMessage.error('上传失败');
			}).catch(() => ElMessage.error('网络错误'));
		},
		initForm() {
			this.form.infoId = -1;
			this.form.infoType = 'other';
			this.form.infoClass = '0';
			this.form.infoContent = '';
			this.form.infoDeadline = '';
			this.form.infoFormat = '';
			this.form.infoSource = '内部';
			this.form.infoProvider = '';
			this.form.infoProvideTime = '';
			this.form.infoCollector = '';
			this.form.infoCollectTime = '';
		}
	}
});

export default infoCollectStore;
